# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'D0aoprz9j2': {  # zs 支付宝（20 ~ 5000) 费率2.5
        'API_KEY': 'VlM2KbXGV65k6pJzDq40mTZ6GyVwITgE',
        'gateway': 'https://www.qqfu.me/api/create',
        'query_gateway': 'https://www.qqfu.me/api/pay_query',
    },
    'BP0y4Ygok4': {  # dwc 支付宝（20 ~ 5000) 费率2.5
        'API_KEY': 'LB7VTJO7FQl2eAS3BhTPrY1KiE8AroFR',
        'gateway': 'https://www.qqfu.me/api/create',
        'query_gateway': 'https://www.qqfu.me/api/pay_query',
    },
    '2Ov9nDJo86': {  # loki 支付宝（20 ~ 5000) 费率2.5
        'API_KEY': 'KoZj7Ty5DXgWjxLBYrdHQZAhDGFJT0OR',
        'gateway': 'https://www.qqfu.me/api/create',
        'query_gateway': 'https://www.qqfu.me/api/pay_query',
    },
    'xXOLdDbLZn': {  # witch 支付宝（20 ~ 5000) 费率2.5
        'API_KEY': 'EHjVrTNsgfv0G3Yv1A1JdNjvZY8cqOBJ',
        'gateway': 'https://www.qqfu.me/api/create',
        'query_gateway': 'https://www.qqfu.me/api/pay_query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    get_first_sign = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s' % (parameter[k])
        get_first_sign = _gen_sign(s)
    get_second_sign = get_first_sign + str(key)
    _LOGGER.info("yurunpay sign str : %s", get_second_sign)
    m = hashlib.md5()
    m.update(get_second_sign.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


# strtolower(md5(md5(out_order_id)+mch_key))
def generate_query_sign(parameter, key):
    s = parameter['out_order_id']
    s = _gen_sign(s)
    s += str(key)
    _LOGGER.info("yurunpay query sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yurunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay'
    return 'alipay'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='get'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('price', '%.2f' % pay_amount),
        ('out_order_id', str(pay.id)),
        ('type', _get_pay_type(service)),
        ('notifyurl', '{}/pay/api/{}/yurunpay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("yurunpay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("yurunpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yurunpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['platform_trade_no']
    total_fee = float(data['realprice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success' and total_fee > 0.0:
        _LOGGER.info('yurunpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('out_order_id', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('yurunpay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('yurunpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['data']['status'])
        total_fee = float(data['data']['realprice'])
        trade_no = data['data']['platform_trade_no']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == 'settled':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('yurunpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
